#!/usr/bin/env python3
"""
部署验证脚本 - 验证双用户语音识别系统
"""
import sys
import asyncio
import traceback
from pathlib import Path

# 添加项目根目录到 Python 路径
project_root = Path(__file__).parent.parent
sys.path.insert(0, str(project_root))

async def verify_imports():
    """验证所有模块导入"""
    print("🔍 验证模块导入...")
    
    try:
        # 验证核心组件导入
        from module_speech.controller.speech_controller import speechController
        from module_speech.controller.speech_api_controller import speechApiController
        from module_speech.controller.speech_client_controller import speechClientController
        from module_speech.controller.websocket_controller import websocket_speech_recognize
        
        # 验证服务层导入
        from module_speech.service.speech_service import SpeechService
        from module_speech.service.speech_client_service import ClientUserService
        from module_speech.service.speech_quota_service import QuotaService
        from module_speech.service.speech_callback_service import CallbackService
        from module_speech.service.speech_usage_service import UsageService
        
        # 验证DAO层导入
        from module_speech.dao.speech_dao import SpeechDao
        from module_speech.dao.speech_client_dao import ClientUserDao
        from module_speech.dao.speech_usage_dao import ClientUsageDao
        
        # 验证工具类导入
        from utils.speech_auth_util import SpeechAuthUtil
        from utils.speech_callback_util import CallbackUtil
        
        # 验证配置导入
        from module_speech.config.speech_config import SpeechConfig
        
        print("✅ 所有模块导入成功")
        return True
        
    except Exception as e:
        print(f"❌ 模块导入失败: {e}")
        print(f"详细错误: {traceback.format_exc()}")
        return False

def verify_routes():
    """验证路由注册"""
    print("🔍 验证路由注册...")
    
    try:
        from module_speech import include_speech_routers
        from fastapi import FastAPI
        
        # 创建测试应用
        test_app = FastAPI()
        include_speech_routers(test_app)
        
        # 检查路由是否注册
        routes = [route.path for route in test_app.routes]
        
        expected_routes = [
            "/speech/upload_and_recognize",  # 系统用户接口
            "/speech/clients",               # 客户端用户管理
            "/api/v1/speech/recognize",      # 客户端API接口
            "/api/v1/speech/quota"           # 配额查询接口
        ]
        
        missing_routes = []
        for expected in expected_routes:
            if not any(expected in route for route in routes):
                missing_routes.append(expected)
        
        if missing_routes:
            print(f"❌ 缺少路由: {missing_routes}")
            return False
        else:
            print("✅ 路由注册验证成功")
            print(f"   - 总路由数: {len(routes)}")
            return True
            
    except Exception as e:
        print(f"❌ 路由验证失败: {e}")
        return False

def verify_database_schema():
    """验证数据库架构"""
    print("🔍 验证数据库架构...")
    
    try:
        # 检查迁移文件是否存在
        migration_file = project_root / "sql" / "V2.0.0__speech_dual_user_migration.sql"
        if not migration_file.exists():
            print("❌ 数据库迁移文件不存在")
            return False
        
        # 检查表结构定义
        with open(migration_file, 'r', encoding='utf-8') as f:
            content = f.read()
        
        required_tables = [
            'speech_client_user',
            'speech_client_usage',
            'speech_record'
        ]
        
        missing_tables = []
        for table in required_tables:
            if f"CREATE TABLE {table}" not in content:
                missing_tables.append(table)
        
        if missing_tables:
            print(f"❌ 缺少表定义: {missing_tables}")
            return False
        else:
            print("✅ 数据库架构验证成功")
            return True
            
    except Exception as e:
        print(f"❌ 数据库架构验证失败: {e}")
        return False

def verify_documentation():
    """验证文档完整性"""
    print("🔍 验证文档完整性...")
    
    try:
        required_docs = [
            project_root / "module_speech" / "README.md",
            project_root / "docs" / "database_schema.md",
            project_root / "调整任务.md"
        ]
        
        missing_docs = []
        for doc in required_docs:
            if not doc.exists():
                missing_docs.append(str(doc))
        
        if missing_docs:
            print(f"❌ 缺少文档: {missing_docs}")
            return False
        else:
            print("✅ 文档完整性验证成功")
            return True
            
    except Exception as e:
        print(f"❌ 文档验证失败: {e}")
        return False

def verify_config():
    """验证配置文件"""
    print("🔍 验证配置文件...")
    
    try:
        from module_speech.config.speech_config import SpeechConfig
        
        # 检查关键配置项
        required_configs = [
            'API_KEY_LENGTH',
            'DEFAULT_MONTHLY_QUOTA',
            'CALLBACK_TIMEOUT',
            'FUNASR_MODEL_PATH'
        ]
        
        missing_configs = []
        for config in required_configs:
            if not hasattr(SpeechConfig, config):
                missing_configs.append(config)
        
        if missing_configs:
            print(f"❌ 缺少配置项: {missing_configs}")
            return False
        else:
            print("✅ 配置文件验证成功")
            return True
            
    except Exception as e:
        print(f"❌ 配置验证失败: {e}")
        return False

async def main():
    """主验证流程"""
    print("🚀 开始验证双用户语音识别系统部署...")
    print("=" * 50)
    
    verification_steps = [
        ("模块导入", verify_imports),
        ("路由注册", verify_routes),
        ("数据库架构", verify_database_schema),
        ("文档完整性", verify_documentation),
        ("配置文件", verify_config)
    ]
    
    results = []
    for step_name, verify_func in verification_steps:
        print(f"\n📋 {step_name} 验证")
        print("-" * 30)
        
        if asyncio.iscoroutinefunction(verify_func):
            result = await verify_func()
        else:
            result = verify_func()
            
        results.append((step_name, result))
    
    # 生成验证报告
    print("\n" + "=" * 50)
    print("📊 验证报告")
    print("=" * 50)
    
    passed = 0
    failed = 0
    
    for step_name, result in results:
        status = "✅ 通过" if result else "❌ 失败"
        print(f"{step_name:15} : {status}")
        if result:
            passed += 1
        else:
            failed += 1
    
    print(f"\n总计: {passed} 项通过, {failed} 项失败")
    
    if failed == 0:
        print("\n🎉 恭喜！双用户语音识别系统部署验证完全通过！")
        print("💡 系统已准备就绪，可以开始使用。")
        
        print("\n📚 快速开始:")
        print("1. 安装依赖: pip install -r requirements-pg.txt")
        print("2. 运行数据库迁移: 执行 V2.0.0__speech_dual_user_migration.sql")
        print("3. 启动服务: python server.py")
        print("4. 访问文档: http://localhost:8000/docs")
        
    else:
        print(f"\n⚠️  发现 {failed} 个问题需要解决后才能正常使用系统。")
        return 1
    
    return 0

if __name__ == "__main__":
    try:
        result = asyncio.run(main())
        sys.exit(result)
    except KeyboardInterrupt:
        print("\n❌ 验证被用户中断")
        sys.exit(1)
    except Exception as e:
        print(f"\n❌ 验证过程中发生错误: {e}")
        print(f"详细错误: {traceback.format_exc()}")
        sys.exit(1) 